package com.stanford.report;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import com.stanford.data.DataUtil;
import com.stanford.data.User;

/**
 * Plot is a utility class that contains simple console
 * output representation of data
 * @author Fatih Sunor
 *
 */
public class Plot {

	/**
	 * Prints the most significant categorical information
	 * @param categorical information
	 * @param topCount significance
	 * @param title to decorate the top part of the report
	 * @return summary
	 */
	public static String top(String[] categorical, int topCount, String title) {
		String result = title + "\n";
		Map<String, Integer> tokenCount = new HashMap<String, Integer>();
		for(String token: categorical){
			if(tokenCount.containsKey(token)){
				tokenCount.put(token, tokenCount.get(token)+1);
			}else{
				tokenCount.put(token, 1);
			}
		}
		return result + printRevertedMapWithCount(tokenCount, topCount);
	}

	private static String printRevertedMapWithCount(Map<String, Integer> tokenCount, int topCount) {
		String result = "";
		Map<Integer,String> revertedMap = DataUtil.revertStringKeyWithIntegerValue(tokenCount);
		SortedMap<Integer, String> sortedMap = new TreeMap<Integer, String>(Collections.reverseOrder());
		sortedMap.putAll(revertedMap);
		SortedMap<Integer, String> shortMap = sortedMap.subMap(sortedMap.firstKey(),topCount);
		for(Integer count: shortMap.keySet()){
			result = result + shortMap.get(count)+": "+count+"\n";
		}
		return result;
	}

	/**
	 * Prints the most significant categorical information
	 * @param users is the data for the categories
	 * @param topCount significance
	 * @param title is to decorate the top part of the report
	 * @return summary
	 */
	public static String top(List<User> users, int topCount, String title) {
		String result = title + "\n";
		Map<String, Integer> tagCount = new HashMap<String, Integer>();
		for(User user: users){
			Map<String, Integer> userTags = user.getTags();
			for(String tag: userTags.keySet()){
				if(tagCount.containsKey(tag)){
					tagCount.put(tag, tagCount.get(tag)+userTags.get(tag));
				}else{
					tagCount.put(tag, userTags.get(tag));
				}
			}
		}
		return result + printRevertedMapWithCount(tagCount, topCount);
	}
}